<template>
  <div class="statistics-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>设备统计</span>
        </div>
      </template>
      
      <!-- 统计卡片 -->
      <div v-if="!loading" class="stats-cards">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-number">{{ totalDevices }}</div>
            <div class="stat-label">总设备数</div>
          </div>
        </el-card>
        
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-number online">{{ onlineDevices }}</div>
            <div class="stat-label">在线设备</div>
          </div>
        </el-card>
        
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-number warning">{{ offlineDevices }}</div>
            <div class="stat-label">离线设备</div>
          </div>
        </el-card>
        
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-number">{{ deviceTypes.length }}</div>
            <div class="stat-label">设备类型</div>
          </div>
        </el-card>
      </div>
      
      <!-- 加载中 -->
      <div v-else class="loading-state">
        <el-loading :visible="true" text="加载统计数据中..." />
      </div>
      
      <!-- 设备类型分布 -->
      <div v-if="!loading && deviceTypes.length > 0" class="chart-section">
        <h3>设备类型分布</h3>
        <div class="chart-container">
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="type-pie-chart">
                <el-empty v-if="!deviceTypeStats.length" description="暂无设备类型数据" />
                <div v-else id="typePieChart" ref="typePieChartRef" class="chart"></div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="type-details">
                <el-table :data="deviceTypeStats" style="width: 100%">
                  <el-table-column prop="type" label="设备类型" />
                  <el-table-column prop="count" label="数量" />
                  <el-table-column prop="percentage" label="占比">
                    <template #default="{ row }">
                      <span>{{ row.percentage }}%</span>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
      
      <!-- 设备在线状态趋势 -->
      <div v-if="!loading && deviceHistory.length > 0" class="chart-section">
        <h3>设备在线状态趋势</h3>
        <div id="statusTrendChart" ref="statusTrendChartRef" class="chart trend-chart"></div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue'
import { deviceApi } from '../services/api'
import { ElMessage } from 'element-plus'

export default {
  name: 'Statistics',
  setup() {
    const loading = ref(true)
    const deviceData = ref([])
    const deviceHistory = ref([])
    const typePieChartRef = ref(null)
    const statusTrendChartRef = ref(null)
    let pieChart = null
    let trendChart = null
    
    // 计算统计数据
    const totalDevices = computed(() => deviceData.value.length)
    const onlineDevices = computed(() => deviceData.value.filter(device => device.status === 'online').length)
    const offlineDevices = computed(() => deviceData.value.filter(device => device.status === 'offline').length)
    
    // 设备类型列表
    const deviceTypes = computed(() => {
      const types = new Set(deviceData.value.map(device => device.type))
      return Array.from(types)
    })
    
    // 设备类型统计
    const deviceTypeStats = computed(() => {
      const stats = {}
      
      deviceData.value.forEach(device => {
        if (!stats[device.type]) {
          stats[device.type] = 0
        }
        stats[device.type]++
      })
      
      return Object.keys(stats).map(type => ({
        type,
        count: stats[type],
        percentage: ((stats[type] / totalDevices.value) * 100).toFixed(1)
      })).sort((a, b) => b.count - a.count)
    })
    
    // 加载设备数据
    const loadDeviceData = async () => {
      try {
        loading.value = true
        const response = await deviceApi.getAllDevices()
        deviceData.value = response.data || []
        
        // 模拟历史数据
        generateMockHistoryData()
      } catch (error) {
        console.error('加载设备数据失败:', error)
        ElMessage.error('加载设备数据失败')
      } finally {
        loading.value = false
      }
    }
    
    // 生成模拟历史数据
    const generateMockHistoryData = () => {
      const now = new Date()
      const history = []
      
      // 生成过去7天的数据
      for (let i = 6; i >= 0; i--) {
        const date = new Date(now)
        date.setDate(date.getDate() - i)
        const dateStr = date.toLocaleDateString()
        
        // 模拟在线率在80%-95%之间变化
        const onlineRate = 0.8 + Math.random() * 0.15
        const online = Math.floor(totalDevices.value * onlineRate)
        const offline = totalDevices.value - online
        
        history.push({
          date: dateStr,
          online,
          offline
        })
      }
      
      deviceHistory.value = history
    }
    
    // 初始化饼图
    const initPieChart = () => {
      if (!typePieChartRef.value || !deviceTypeStats.value.length) return
      
      const ctx = typePieChartRef.value.getContext('2d')
      if (pieChart) pieChart.destroy()
      
      pieChart = new Chart(ctx, {
        type: 'pie',
        data: {
          labels: deviceTypeStats.value.map(item => item.type),
          datasets: [{
            data: deviceTypeStats.value.map(item => item.count),
            backgroundColor: [
              '#0088FE',
              '#00C49F',
              '#FFBB28',
              '#FF8042',
              '#8884d8',
              '#82ca9d'
            ]
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: {
              position: 'bottom'
            },
            tooltip: {
              callbacks: {
                label: function(context) {
                  const label = context.label || ''
                  const value = context.parsed || 0
                  const percentage = ((value / totalDevices.value) * 100).toFixed(1)
                  return `${label}: ${value} (${percentage}%)`
                }
              }
            }
          }
        }
      })
    }
    
    // 初始化趋势图
    const initTrendChart = () => {
      if (!statusTrendChartRef.value || !deviceHistory.value.length) return
      
      const ctx = statusTrendChartRef.value.getContext('2d')
      if (trendChart) trendChart.destroy()
      
      trendChart = new Chart(ctx, {
        type: 'line',
        data: {
          labels: deviceHistory.value.map(item => item.date),
          datasets: [
            {
              label: '在线设备',
              data: deviceHistory.value.map(item => item.online),
              borderColor: '#00C49F',
              backgroundColor: 'rgba(0, 196, 159, 0.1)',
              fill: true
            },
            {
              label: '离线设备',
              data: deviceHistory.value.map(item => item.offline),
              borderColor: '#FF8042',
              backgroundColor: 'rgba(255, 128, 66, 0.1)',
              fill: true
            }
          ]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          scales: {
            y: {
              beginAtZero: true,
              ticks: {
                precision: 0
              }
            }
          }
        }
      })
    }
    
    // 监听数据变化，重新渲染图表
    watch([deviceTypeStats, deviceHistory], () => {
      // 延迟执行，确保DOM已更新
      setTimeout(() => {
        initPieChart()
        initTrendChart()
      }, 0)
    }, { deep: true })
    
    // 组件挂载时加载数据
    onMounted(async () => {
      await loadDeviceData()
      
      // 动态导入Chart.js
      if (typeof Chart === 'undefined') {
        const { Chart } = await import('chart.js/auto')
        window.Chart = Chart
        
        // 延迟初始化图表
        setTimeout(() => {
          initPieChart()
          initTrendChart()
        }, 0)
      }
    })
    
    return {
      loading,
      deviceData,
      deviceHistory,
      totalDevices,
      onlineDevices,
      offlineDevices,
      deviceTypes,
      deviceTypeStats,
      typePieChartRef,
      statusTrendChartRef
    }
  }
}
</script>

<style scoped>
.statistics-container {
  padding: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
  gap: 15px;
  margin-bottom: 20px;
}

.stat-card {
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.stat-content {
  text-align: center;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 8px;
}

.stat-number.online {
  color: #00C49F;
}

.stat-number.warning {
  color: #FF8042;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px 0;
}

.chart-section {
  margin-top: 25px;
}

.chart-section h3 {
  margin-bottom: 15px;
  color: #303133;
  font-size: 18px;
}

.chart-container {
  margin-bottom: 15px;
}

.type-pie-chart {
  height: 250px;
}

.chart {
  height: 100%;
  width: 100%;
}

.trend-chart {
  height: 300px;
}

/* 表格容器，确保在小屏幕上可以滚动 */
.type-details {
  overflow-x: auto;
}

/* 响应式样式 */
@media (max-width: 768px) {
  .statistics-container {
    padding: 8px;
  }
  
  .stats-cards {
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
  }
  
  .stat-card {
    height: 90px;
  }
  
  .stat-number {
    font-size: 20px;
    margin-bottom: 6px;
  }
  
  .stat-label {
    font-size: 13px;
  }
  
  .chart-section {
    margin-top: 20px;
  }
  
  .chart-section h3 {
    font-size: 16px;
    margin-bottom: 12px;
  }
  
  .type-pie-chart {
    height: 200px;
  }
  
  .trend-chart {
    height: 250px;
  }
  
  /* 调整表格在小屏幕上的显示 */
  :deep(.el-table) {
    font-size: 13px;
  }
  
  :deep(.el-table th),
  :deep(.el-table td) {
    padding: 8px;
  }
}

@media (max-width: 480px) {
  /* 进一步调整在极小屏幕上的显示 */
  .stats-cards {
    grid-template-columns: 1fr;
    gap: 10px;
  }
  
  .stat-card {
    height: 80px;
  }
  
  .stat-number {
    font-size: 18px;
    margin-bottom: 4px;
  }
  
  .stat-label {
    font-size: 12px;
  }
  
  .chart-section h3 {
    font-size: 15px;
  }
  
  .type-pie-chart {
    height: 180px;
  }
  
  .trend-chart {
    height: 200px;
  }
  
  /* 优化表格在极小屏幕上的显示 */
  :deep(.el-table) {
    font-size: 12px;
  }
  
  :deep(.el-table th),
  :deep(.el-table td) {
    padding: 6px;
  }
  
  /* 调整饼图选项 */
  .chart-section .el-row {
    flex-direction: column;
  }
  
  .chart-section .el-col {
    width: 100% !important;
    margin-bottom: 15px;
  }
  
  /* 确保表格在极小屏幕上可以滚动 */
  .type-details {
    width: 100%;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
  }
}
</style>